#include "TiledLayer.h"
#include "base/ccMacros.h"
#include "base/ccUTF8.h"
#include "base/CCDirector.h"
#include "renderer/CCGLProgramCache.h"
#include "renderer/ccGLStateCache.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCTextureCache.h"
#include "renderer/CCVertexIndexBuffer.h"
#include "renderer/CCGLProgram.h"

#include "TiledParser.h"
#include "deprecated/CCString.h"

namespace Tiled {

TmxLayer * TmxLayer::create(TmxLayerInfo *layerInfo, TmxMapInfo *mapInfo)
{
    TmxLayer *ret = new (std::nothrow) TmxLayer();
    if (ret->initWithTilesetInfo(layerInfo, mapInfo))
    {
        ret->autorelease();
        return ret;
    }
    return nullptr;
}

bool TmxLayer::initWithTilesetInfo(TmxLayerInfo *layerInfo, TmxMapInfo *mapInfo)
{    
    setOpacity( layerInfo->opacity );
	
	this->setName(layerInfo->name);

	int width = mapInfo->getMapSize().width;
	int height = mapInfo->getMapSize().height;

	for (int y = 0; y < height; ++y)
	{
		for (int x = 0; x < width; ++x)
		{
			int gid = layerInfo->tiles[y * width + x];
			if (gid != 0) {
				Sprite* tile = Sprite::createWithSpriteFrame(mapInfo->getTile(gid));
				tile->setPosition(mapInfo->tileIndexToPos(x, y));
				tile->setAnchorPoint(Point(0, 0));
				this->addChild(tile);
			}
		}
	}
	//this->setScale(0.5);
    return true;
}

TmxLayer::TmxLayer()
{
}

TmxLayer::~TmxLayer()
{
}

std::string TmxLayer::getLayerName()
{
	return _layerInfo->name;
}

}


